package com.example.xd.fmpeg_test.weight;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.example.xd.fmpeg_test.R;

/**
 * Created by RWL on 2018/3/16.
 */

public class RectangleLayout extends FrameLayout {

    private int ratio;

    public RectangleLayout(Context context) {
        super(context);
    }

    public RectangleLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RectangleLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RectangleLayout);
        ratio = a.getInteger(R.styleable.RectangleLayout_ratio, 0);
        a.recycle();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public RectangleLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        float r = 1;
        switch (ratio){
            case 0 :
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                return;
            case 1 :
                r = 1;
                break;
            case 2 :
                r = 4.0f / 3;
                break;
            case 3 :
                r = 16.0f / 9;
                break;
            case 4 :
                r = 16.0f / 14;
                break;
            case 5:
                r = 16.0f / 10.5f;
                break;
        }
        setMeasuredDimension(getDefaultSize(0, widthMeasureSpec),
                getDefaultSize(0, heightMeasureSpec));

        int childWidthSize = getMeasuredWidth();
        // 高度和宽度一样
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(
                (int) (childWidthSize / r), MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public void setRatio(int ratio) {
        this.ratio = ratio;
    }
}
